#!/usr/bin/python
import sys, os, cgi, time, urllib2, threading
import subprocess
import SimpleHTTPServer, SocketServer
from grabber import progress
from sql import SQL
from megaupload import *
from rapidshare import *


def df(filesystem):
    """Report disk usage.
    Return a dictionary with total, used, available. Sizes are reported
    in blocks of 1024 bytes."""
    output = subprocess.Popen(['/bin/df', filesystem], stdout=subprocess.PIPE).communicate()[0]
    lines = output.split('\n')
    fs, blocks_total, blocks_used, blocks_available, used, mount =lines[1].split()
    blocks_total = int(blocks_total)
    blocks_used = int(blocks_used)
    blocks_available = int(blocks_available)
    return dict(total=blocks_total, used=blocks_used, available=blocks_available)

def from_megaupload(url):
  """Check if this is a megaupload link"""
  return (url.startswith("megaupload.com") or
          url.startswith("www.megaupload.com") or
          url.startswith("http://megaupload.com") or
          url.startswith("http://www.megaupload.com"))

def from_rapidshare(url):
  """Check if this is a rapidshare link"""
  return (url.startswith("rapidshare") or
          url.startswith("www.rapidshare.com") or
          url.startswith("http://rapidshare.com") or
          url.startswith("http://www.rapidshare.com"))


class Servidor(SimpleHTTPServer.SimpleHTTPRequestHandler):
  '''Clase del servidor web'''
  thread = None
  def do_POST(self):
    print "Recibiendo POST"

    #separamos los elementos
    (scheme, netloc, path, query, fragment) = urllib2.urlparse.urlsplit(self.path)
    pagina = path.split("/")[-1]
    parametros = cgi.parse_qs(query, keep_blank_values=1)

    ctype, pdict = cgi.parse_header(self.headers.getheader('content-type'))
    length = int(self.headers.getheader('content-length'))
    if ctype == 'multipart/form-data':
      self.body = cgi.parse_multipart(self.rfile, pdict)
    elif ctype == 'application/x-www-form-urlencoded':
      # Datos formulario
      qs = self.rfile.read(length)
      # Datos formulario parseados
      self.body = cgi.parse_qs(qs, keep_blank_values=1)
      if pagina == "config":
        print self.body
        bd = SQL()
        bd.setparameter("concurrency",self.body["concurrency"][0])
        bd.setparameter("download_limit",self.body["download_limit"][0])
        bd.setparameter("theme",self.body["theme"][0])
        bd.setparameter("dest_path",self.body["dest_path"][0])
        bd.setparameter("mu_user",self.body["mu_user"][0])
        bd.setparameter("cdn",self.body["cdn"][0])
        bd.setparameter("cdn_path",self.body["cdn_path"][0])
        if self.body["mu_pwd"][0] <> '':
          bd.setparameter("mu_pwd",self.body["mu_pwd"][0])
#        if self.body["rs_user"][0] <> '':
#          bd.setparameter("rs_user",self.body["rs_user"][0]);
#        if self.body["rs_pwd"][0] <> '':
#          bd.setparameter("rs_pwd",self.body["rs_pwd"][0]);
        bd.close()
        M = Megaupload()
        M.set_access_cookie()
        self.send_redirect("/config")
      else:
        contenido = self.p_indice()
        self.send_content(contenido.encode('utf-8'))
        self.add_links(self.body)
    elif pagina.startswith("removelink"):
      # Esto no va aqui, hay que moverlo al GET
      bd = SQL()
      bd.removelink(pagina.split("=")[0])
      self.body = {}
      contenido = self.p_list()
      self.send_content(contenido.encode('utf-8'))
      return
    else:
      self.body = {}
      contenido = self.p_indice()
      self.send_content(contenido.encode('utf-8'))
    return

  def do_GET(self):

    #separamos los elementos
    (scheme, netloc, path, query, fragment) = urllib2.urlparse.urlsplit(self.path)

    print scheme
    print netloc
    print path
    print query
    print fragment
    print ("Parametros: %s" % cgi.parse_qs(query, keep_blank_values=1) )
# FOR DEBUG UNCOMMENT
#    contenido = self.p_list()
#    self.send_content(contenido.encode('utf-8'))
    try:
      pagina = path.split("/")[-1]
      parametros = cgi.parse_qs(query, keep_blank_values=1)
      if pagina == "list":
        contenido = self.p_list()
        self.send_content(contenido.encode('utf-8'))
      elif pagina == "config":
        contenido = self.p_config()
        self.send_content(contenido.encode('utf-8'))
      elif pagina == "historic":
        contenido = self.p_historic()
        self.send_content(contenido.encode('utf-8'))
      elif pagina == "ajax_list":
        contenido = self.p_ajax_list()
        self.send_content(contenido.encode('utf-8'))
      elif pagina == "disk_usage":
        contenido = self.p_ajax_disk_usage()
        self.send_content(contenido.encode('utf-8'))
      elif pagina == "view_folder":
        contenido = self.p_view_folder()
        self.send_content(contenido.encode('utf-8'))
      elif pagina == "restartlink":
        db = SQL()
        db.unlocklink(parametros["url"][0])
        db.close()
        self.send_redirect("/list")
      elif pagina == "delete":
        contenido = self.p_delete(parametros["file"][0])
        self.send_content(contenido.encode('utf-8'))
      elif pagina == "open_folder":
        contenido = self.p_open_folder(parametros["dir"][0])
        self.send_content(contenido.encode('utf-8'))        
      elif pagina == "extract":
        contenido = self.p_extract(parametros["file"][0])
        self.send_content(contenido.encode('utf-8'))        
      elif pagina == "deletehistoric":
        db = SQL()
        db.delete_historic()
        db.close()
        self.send_redirect("/historic")
      elif pagina == "removelink":
        db = SQL()
        db.removelink(parametros["url"][0])
        db.close()
        self.send_redirect("/list")
      elif pagina == "pauselink":
        db = SQL()
        db.pauselink(parametros["url"][0])
        db.close()
        self.send_redirect("/list")
        
      elif pagina == "removefailed":
        db = SQL()
        db.removefailed()
        db.close()
        self.send_redirect("/list")
      elif pagina == "stop":
        print queue
        id = parametros["id"]
        for x in queue:
          if x == id:
            print "OK!"
            db = SQL()
            db.pauselink(queue[x]["url"][0])
            db.close()
            th = queue[x]["object"]
            th.quit()
        self.send_redirect("/list")
      elif pagina == "kill":
         contenido = "<body style='background:#000;color:#F00;margin:0;padding:20% 0;width:100%;height:100%;text-align:center;'><h1 style=''>rinkoki<br />is dead<br />&#134;</h1></body>"
         self.send_content(contenido)
         os._exit(0)
      elif pagina == "listmin":
        contenido = self.p_list_min()
        self.send_content(contenido.encode('utf-8'))
      elif path == "/":
        contenido = self.p_indice()
        self.send_content(contenido.encode('utf-8'))
      else:
        self.send_fs(pagina)
    except ImportError:
      self.send_error(405)
      return
    return

  def add_links (self, links):
    global rapid_slot
    urls = links['links']
    M = Megaupload()
    R = Rapidshare()
    for url in urls[0].split():
      if from_megaupload(url):
        db = SQL()
        if db.checklink(url) == None:
          db.addlink(url)
          if not M.download(url,None,1):
            db.updatelinkname(url,"Failed")
            db.failed(url)
          else:
            db.unlocklink(url)
        db.close()
      if from_rapidshare(url):
        db = SQL()
        if db.checklink(url) == None:
          db.addlink(url)
          if not R.download(url,None,1,rapid_slot):
            db.updatelinkname(url,"Failed")
            db.failed(url)
          else:
            db.unlocklink(url)
        db.close()
    return

  def send_fs(self, pagina):
    f = self.send_head()
    if f:
      self.copyfile(f, self.wfile)
      f.close()

  def send_content(self, contenido):
    #contestamos al browser
    self.send_response(200)
    self.send_header("content-type", "text/html")
    self.send_header("content-length", len(contenido))
    self.end_headers()
    self.wfile.write(contenido)
    return

  def send_redirect(self, url):
    self.send_response(301)
    self.send_header("Location", url)
    self.end_headers()


  def p_indice(self):
    h = do_HTML()
    h.body = """</div>
      <form method="POST" action="">
	<div id="enlaces">
        <label id="links">Links</label><textarea id="listlinks" name="links" rows="10" cols="50"></textarea>
	   <br />
        <!--
	   <label for="clearname">Nombre del paquete<input type="text" name="clearname" id="clearname" />
	   <br />
	   <label for="password">Password<input type="text" name="password" id="password" /><br />-->
        <input type="submit" value="Enviar"> <input type="button" id="checklinks" value="Check Links" onclick="linkchecker();" />
        <div id="checked_links"></div>
	</div>

        </form>

    """
    return h.process()

  def p_ajax_list(self):
    h = do_HTML()
    h.body = ""
    h.head = ""
    h.foot = ""
    for x in queue:
      h.body = h.body + ("<ul id='downloading'><li class='item'><ul><li class='fn'>%s</li><li class='fs'>%s</li><li class='fp'><div style='background-position: -%dpx 0;'></div><li class='fr'>%s/s</li><li class='rt'>%s</li><li>%s</li></ul></li></ul>" %
      (queue[x]["progress"].basename,queue[x]["progress"].fsize,(100-(queue[x]["progress"].re.fraction_read()*100)),
      progress.format_number(queue[x]["progress"].re.ave_rate),
      progress.format_time(queue[x]["progress"].re.remaining_time()),
      queue[x]["error"] ))
      
    if h.body == "":
      h.body = "<h2>Nothing to download</h2>"

    return h.process()
    
  def p_ajax_disk_usage(self):
    h = do_HTML()
    h.head="""<head></head>"""        
    bd = SQL()
    disk1 = df(os.getcwd())
    disk1['name'] = 'Local'
    disk1['usedwidth'] = (disk1['used']*100)/disk1['total']
    disk1['availablewidth'] = 100-disk1['usedwidth']
    
    if os.path.isdir(bd.getparameter("dest_path")):    
        disk2 = df(bd.getparameter("dest_path"))
        disk2['name'] = "<a href='/view_folder'>" + bd.getparameter("dest_path") + "</a>"
        disk2['usedwidth'] = disk2['used']*100/disk2['total']
        disk2['availablewidth'] = 100-disk2['usedwidth']
        no_dest = ""
    else:
        disk2 = dict(total=1, used=1, available=1, name="Not available", usedwidth=100, availablewidth=0)
        no_dest = "<h1>No destination path found</h1>"
        
    h.body="""<div class='drive'><span class='disk-name'>%s</span>
        <div id='path-local'></div>        
        <div class='disk-total' style='background-position:%d%% 100%%'>
            <div class='disk-used'>%sM</div>
            <div class='disk-available'>%sM</div>
        </div>
        <span class='disk-size'>%s M</span>
        </div>
         <div class='drive'>
        <span class='disk-name'>%s</span>
        <div id='path-dest'></div>                
        <div class='disk-total' style='background-position:%d%% 100%%'>
            <div class='disk-used'>%sM</div>
            <div class='disk-available'>%sM</div>
        </div>
        <span class='disk-size'>%s M</span>
        %s</div>""" % (disk1['name'], 100-disk1['usedwidth'], disk1['used']/1024, disk1['available']/1024, disk1['total']/1024, disk2['name'], 100-disk2['usedwidth'], disk2['used']/1024, disk2['available']/1024, disk2['total']/1024, no_dest)
            
    return h.process()

  def p_historic(self):
    h = do_HTML()
    db = SQL()
    all_links = db.gethistoric()
    h.body = h.body + ("<h1>Historic...</h1><table><thead><tr><td></td><td><a href='/deletehistoric?all=1'>Delete historic</a></td></tr></thead><tbody id='historic'>")
    for tupla in all_links:
      h.body = h.body + ("<tr><td>%s</td><td>%s</td><td><a href='/restartlink?url=%s' class='restartlink'>Retry</a></td><td>%s</td></tr>\n" % (tupla[0], tupla[1], tupla[0], tupla[3]))
    h.body = h.body + ("</tbody></table>")
    return h.process()

  def p_list(self):
    global queue

    h = do_HTML()
    #      print queue[x]["progress"].last_amount_read
    db = SQL()
    all_links = db.getall()
    h.body = """
   <div id='links_list'>
    <table summary="Queue downloads">
      <thead>
          <caption>Queue downloads</caption>
          <tr>
             <th>Filename</th>
             <th>Status</th>
             <th>Actions</th>
          </tr>
      </thead>          
       <tbody id="list">"""
      
    h.body = h.body + """
      </tbody>
      <tfoot>
         <tr>
            <td colspan="3">
               <a href='/removefailed' id='remove_fail_links'>Remove failed downloads</a>
            </td>
         </tr>
      </tfoot>
      </table>
      <script type='text/javascript'>$("#list").load("/listmin");var refreshId2 = setInterval(function() {$("#list").load("/listmin");},10000);</script>
    """
    return h.process()

  def p_list_min(self):
    global queue

    h = do_HTML()
    h.head=""""""
    db = SQL()
    all_links = db.getall()
    for tupla in all_links:
      name = tupla[1]
      if tupla[3] == 0:
         status = 0
      elif tupla[3] == 1:
         status = 1
      elif tupla[3] == 2:
         status = 2
      elif tupla[3] == 3:
         status = 3
      elif tupla[3] == 4:
         status = 4
         
      if name == "Failed":
        name = tupla[0]
      h.body = h.body + ("<tr><td>%s</td><td class='%d'><u>%d</u></td>" % (name, status, status)) + ("""<td><a href='/restartlink?url=%s' class='restartlink'>Retry</a><a href='/removelink?url=%s' class='removelink'>Delete</a><a href='/pauselink?url=%s' class='pauselink'>Pause</a><a href='%s'>Open in MU</a></td>""" % (tupla[0], tupla[0], tupla[0], tupla[0]))
    return h.process()

  def p_remove_link(self):
     h = do_HTML()
     h.body = """
       <h1>Removed</h1>
     """
     return h.process()
    
  def p_open_folder (self, url):
     h = do_HTML()
     h.head = ""
     db = SQL()
     dir = db.getparameter("dest_path") + "/" + url
     files = os.listdir(dir.encode('utf-8'))
     files.sort()
     h.body = "<li class='dir'><u>" + url + "/..</u></li>"
     for f in files :
        if os.path.isdir(dir.encode('utf-8') + "/" + f) :
           h.body = h.body + "<li class='dir'><u>" + url + f.decode('latin-1') + "</u></li>"
        else:
           h.body = h.body + "<li class='rar'><u>" + url + f.decode('latin-1') + "</u></li>"
       
     h.body = h.body + "<script type='text/javascript'>init_view_folder()</script>"
       
     db.close()
     return h.process()        
      
      
  # Metodo para mostrar todos los archivos de la carpeta destino.
  # La idea es hacer un explorador de ficheros donde se pueda descomprimir el contenido, eliminar ficheros, etc...
  def p_view_folder ( self ):
    h = do_HTML()      
    db = SQL()      
    dir = db.getparameter("dest_path")
    files = os.listdir(dir.encode('utf-8'))
    files.sort()

    h.body = "<div id='output'>rinkoki@" + db.getparameter("dest_path") + "$ <span class='blink'>_</span></div>"
    h.body = h.body + "<div id='basedir'></dir>"
    h.body = h.body + "<div id='method_view_div'><select id='method_view'><option value='icons'>Icons</option><option value='list'>List</option></select></div>"
    h.body = h.body + "<div class='context' id='context_rar'><ul><li id='rar_extract'>Extract</li><li id='rar_extractto'>Extract to...</li><li id='rar_delete'>Delete</li><li id='rar_rename'>Rename</li></ul></div>"
    h.body = h.body + "<div class='context' id='context_dir'><ul><li id='dir_open'>Open</li><li id='rar_delete'>Delete</li><li id='dir_rename'>Rename</li></ul></div>"    
    h.body = h.body + "<ul id='view_folder'>"
    
    for f in files :
      if os.path.isdir(dir.encode('utf-8') + "/" + f) :
        h.body = h.body + "<li class='dir'><u>" + f.decode('latin-1') + "</u><ul class='menufile' id='" + f.decode('latin-1') + "'><li class='open'>Open</li><li class='rename'>Rename</li></ul></li>"
      else:
        h.body = h.body + "<li class='rar'><u>" + f.decode('latin-1') + "</u></li>"
        
    db.close()
    h.body = h.body + "</ul><div class='clear'></div></div>"
    return h.process()

  def p_extract ( self, url ):
    h = do_HTML()
    db = SQL()
    h.head="""<head></head>"""
    path = db.getparameter("dest_path") + "/"
    output = subprocess.Popen(['unrar', 'x', '-y', path + url, path], stdout=subprocess.PIPE).communicate()[0]
    h.body = output + "rinkoki@" + db.getparameter("dest_path") + "$ <span class='blink'>_</span>"
    return h.process()

  def p_delete ( self, url ):
    h = do_HTML()
    db = SQL()
    h.head="<head></head>"
    path = db.getparameter("dest_path") + "/" + url
    os.unlink(path)
    h.body = "rinkoki@" + db.getparameter("dest_path") + "$ rm " + url + "<br />rinkoki@" + db.getparameter("dest_path") + "$ <span class='blink'>_</span>"
    return h.process()
     
  def p_config(self):
      h = do_HTML()
      db = SQL()
      
      dir = os.getcwd() + "/themes"
      files = os.listdir(dir.encode('utf-8'))
      files.sort()
      print files
      selects = ''
      for f in files :
         if f != '.svn':
            selects = selects + "<option value='" + f.decode('latin-1')
            if f == db.getparameter("theme"):
               selects = selects + "' selected='selected"
            selects = selects + "'>" + f.decode('latin-1') + "</option>"
      s_cdn = "<option value='"
      if db.getparameter("cdn") == "0":
        s_cdn = s_cdn + "0' selected='selected'>No</option> <option value='1'>Yes</option>"
      else:
        s_cdn = s_cdn + "1' selected='selected'>Yes</option> <option value='0'>No</option>"
      h.body = ("""
      <div id='config'>
      <form method='POST' action='config'> 
         <fieldset id='access_mu_form'>
            <legend>Datos de Acceso de Megaupload</legend>      
            <label>Usuario</label>
            <input type='text' name='mu_user' value='%s'/><br /> 
            <label>Password</label>
            <input type='password' name='mu_pwd' value='%s' /> <span class='view_password'><img src='images/view.png' alt='View password'></span><br />
         </fieldset>
         <fieldset id='access_rs_form'>
            <legend>Datos de Acceso de Rapidshare</legend>
            <label>Usuario</label>
            <input type='text' name='rs_usr' value='%s'/><br /> 
            <label>Password</label>
            <input type='password' name='rs_pwd' value='%s' /><br /> 
         </fieldset>
         <fieldset>
            <legend>Configuracion general</legend>
            <label>Concurrencia</label> 
            <input type='text' name='concurrency' value='%s'/><br />	
            <label>Download Limit</label> 
            <input type='text' name='download_limit' value='%s'/><br />	
            <label>Theme</label> <select name='theme' />%s</select><br />
            <label>Directorio descarga</label> 
            <input type='text' name='dest_path' value='%s' /><br />
            <label>CDN</label> <select name='cdn' />%s</select><br />
            <label>CDN path</label>
            <input type='text' name='cdn_path' value='%s' /><br />
         </fieldset>	
         <input type='submit' value='Enviar' />
      </form>
      </div>""" % (db.getparameter("mu_user"), db.getparameter("mu_pwd"),db.getparameter("rs_user"), db.getparameter("rs_pwd"), db.getparameter("concurrency"), db.getparameter("download_limit"), selects, db.getparameter("dest_path"), s_cdn, db.getparameter("cdn_path")))
      db.close()
      return h.process()

class do_HTML:

   body = ""
   foot = """
         <div class='clear'></div>
         <div id='foot'></div>
      </div>
   </body>
</html>
  """

   def __init__(self):
      self.head = self.get_head()

   def get_head(self):
      bd = SQL()
      disk1 = df(os.getcwd())
      disk1['name'] = 'Local'
      disk1['usedwidth'] = (disk1['used']*100)/disk1['total']
      disk1['availablewidth'] = 100-disk1['usedwidth']

      if os.path.isdir(bd.getparameter("dest_path")):    
         disk2 = df(bd.getparameter("dest_path"))
         disk2['name'] = "<a href='/view_folder'>" + bd.getparameter("dest_path") + "</a>"
         disk2['usedwidth'] = disk2['used']*100/disk2['total']
         disk2['availablewidth'] = 100-disk2['usedwidth']
         no_dest = ""
      else:
         disk2 = dict(total=1, used=1, available=1, name="Not available", usedwidth=100, availablewidth=0)
         no_dest = "<h1>No destination path found</h1>"
      if bd.getparameter("cdn") == 1:
        CDN = 'http://jlpoveda.com/rinkoki'
      else:
        CDN = ''
      head = """
   <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
   <html xml:lang="es_ES">
   <head>
     <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-15" />
     <title>Rinkoki - Download Center</title>
     <link rel="icon" href="%s/themes/%s/favicon.png" type="image/png" />
     <link media="only screen and (max-device-width: 480px)" href="%s/themes/iphone/styles.css" type="text/css" rel="stylesheet" /> 
     <link media="screen and (min-device-width: 481px)" href="%s/themes/%s/styles.css" type="text/css" rel="stylesheet" />
     <script type="text/javascript" src="%s/js/jquery-1.3.2.min.js"></script>
     <script type="text/javascript" src="%s/js/jquery.contextmenu.r2.packed.js"></script>
     <script type="text/javascript" src="%s/js/autoresize.jquery.min.js"></script>
     <script type="text/javascript" src="%s/js/rinkoki.js"></script>     
     <script type="text/javascript" src="%s/js/ui.core.js"></script>
     <script type="text/javascript" src="%s/js/ui.draggable.js"></script>
     <script type="text/javascript" src="%s/js/ui.droppable.js"></script>
     <script type="text/javascript" src="%s/js/linkchecker.js"></script>

   </head>
   <body id='body'>
   <div id='container'>
       <div id='container-header'>
           <div id='header'>
           </div>

           <div id='navigator'>
               <ul>
               <li><a href='/' id='h' title='Home'>Home</a></li>
               <li><a href='/list' id='d' title='Descargas'>Descargas</a></li>
               <li><a href='/historic' id='l' title='Historico de Descargas'>Historico de Descargas</a></li>
               <li><a href='/config' id='c' title='Config'>Config</a></li>
               <li><a href='/kill' id='e' title='Exit'>Shutdown</a></li>
               </ul>
           </div>

       </div>
      <div id='pannels'>
           <div id='disk-usage'>
               <span class='disk-name'>%s</span>
               <div class='disk-total'>
                   <div class='disk-used' style='width:%d%%'>%sM</div>
                   <div class='disk-available' style='width:%d%%'>%sM</div>
               </div>
               <span class='disk-name'>%s M</span>
               <br />
               <span class='disk-name'>%s</span>
               <div class='disk-total'>
                   <div class='disk-used' style='width:%d%%'>%sM</div>
                   <div class='disk-available' style='width:%d%%'>%sM</div>
               </div>
               <span class='disk-name'>%s M</span>
               %s
           </div>
        
            <h1>Now downloading...</h1>
            <div id='now_downloading'></div>
      </div>

     """ % (CDN, bd.getparameter("theme"), CDN, CDN, bd.getparameter("theme"), CDN, CDN, CDN, CDN, CDN, CDN, CDN, CDN, disk1['name'], disk1['usedwidth'], disk1['used']/1024, disk1['availablewidth'], disk1['available']/1024, disk1['total']/1024, disk2['name'], disk2['usedwidth'], disk2['used']/1024, disk2['availablewidth'], disk2['available']/1024, disk2['total']/1024, no_dest)

      return head

   def process(self):
      contenido = self.head + self.body + self.foot
      return contenido

class MyServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer):
   allow_reuse_address = True
   pass

# Diccionario con la informacion de ancho de banda y transferencias online.
queue = {}
# We want threads as process
local = threading.local()
# Flag of slot of free rapidshare. Mutable variable ;-)
rapid_slot = ["no"]

def BuclePrincipal():
  global rapid_slot
  print ("DEBUG: Slot rapidshare: %s" % rapid_slot[0])
  db = SQL()
#  print threading.enumerate()
  if len(threading.enumerate()) < 2+int(db.getparameter("concurrency")):
    if rapid_slot[0] == "no":
      rapid_slot[0] = "yes"
      link = db.catchlink_rapidshare()
      if link == None:
        link = db.catchlink_megaupload()
    else:
      link = db.catchlink_megaupload()
    if link != None:
      print link[0]
      if from_megaupload(link[0]):
        print "Megaupload link detected"
        local.mg = Megaupload()
        th = threading.Thread(target=local.mg.download, args=(link[0],queue,0, ))
        th.start()
      elif from_rapidshare(link[0]):
        print "Rapidshare link detected"
        local.rs = Rapidshare()
        th = threading.Thread(target=local.rs.download, args=(link[0], queue,0,rapid_slot, ))
        th.start()
  db.close()

  global t
  t = threading.Timer(5.0, BuclePrincipal)
  t.start()


if __name__=="__main__":
  if len(sys.argv) != 2 or not sys.argv[1].isdigit():
    print "Usage: server.py <port>"
    sys.exit()
  db = SQL()
  db.resetstatus()
  db.close()
  t=threading.Timer(5.0, BuclePrincipal)
  t.start()
  port = int(sys.argv[1])
  s = MyServer(('', port), Servidor)
#  s.thread = th
  s.serve_forever()
